<!-- src/views/Auth.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { fetchData } from '../api';
import type { ErrorMsg } from '../types/ErrorMsg';
import { Code } from '../constant/Code';

// 当前面板状态：login 或 register
const activePanel = ref('login');

// 登录表单数据
const loginForm = ref({
  phone: '',
  code: '',
});

// 注册表单数据
const registerForm = ref({
  phone: '',
  code: '',
  // password: '',
});

// 登录表单引用
const loginFormRef = ref<FormInstance>();
// 注册表单引用
const registerFormRef = ref<FormInstance>();

// 登录表单验证规则
const loginRules: FormRules = {
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
};

// 注册表单验证规则
const registerRules: FormRules = {
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  // password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

// 发送验证码
const countdown = ref(0); // 倒计时秒数
let timer: number | null = null; // 定时器
const sendCode = async (type: 'login' | 'register') => {
  if (type === 'login') {
    if (!loginForm.value.phone) {
      ElMessage.error('请输入手机号');
      return;
    }
  }else if (type === 'register') {
    if (!registerForm.value.phone) {
      ElMessage.error('请输入手机号');
      return;
    }
  }
  if (countdown.value > 0) return; // 如果正在倒计时，直接返回

  // 这里可以调用发送验证码的 API
  try {
    await fetchData('/api/sms/send/register','POST',{
      originMobile: type === 'login' ? loginForm.value.phone:registerForm.value.phone,
      mobilePrefix: '+86'
    })
    ElMessage.success('验证码已发送');
  } catch (error: any | ErrorMsg) {
    console.log(error.code);
    if(error.code){
      ElMessage.error('验证码发送失败:'+(error as ErrorMsg).msg);
      if(error.code === Code.TIME_LIMIT){
        const reg = /\d+/;
        const result = reg.exec((error as ErrorMsg).msg)!;
        countdown.value = parseInt(result[0]);
      }
    }else{
      ElMessage.error('验证码发送失败:'+error.toString());
    }
  }
  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0 && timer) {
      clearInterval(timer); // 倒计时结束，清除定时器
      timer = null;
    }
  }, 1000);
};
// 处理登录
const handleLogin = () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      // 这里可以调用登录的 API
      try {
        await fetchData('/api/sms/validate/register','POST',{
          originMobile: loginForm.value.phone,
          mobilePrefix: '+86',
          code: loginForm.value.code
        })
        ElMessage.success('登录成功');
      } catch (error: any | ErrorMsg) {
        console.log(error);
        ElMessage.error('登录失败:'+error.toString());
      }
    } else {
      ElMessage.error('请填写完整信息');
    }
  });
};

// 处理注册
const handleRegister = () => {
  registerFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await fetchData('/api/sms/validate/register','POST',{
          originMobile: loginForm.value.phone,
          mobilePrefix: '+86',
          code: loginForm.value.code
        })
        ElMessage.success('注册成功');
      } catch (error: any | ErrorMsg) {
        console.log(error);
        ElMessage.error('注册失败:'+error.toString());
      }
    } else {
      ElMessage.error('请填写完整信息');
    }
  });
};
</script>

<template>
  <div class="auth-container">
    <el-tabs v-model="activePanel" stretch>
      <el-tab-pane label="登录" name="login">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="80px">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="loginForm.code" placeholder="请输入验证码">
              <template #append>
                <el-button @click="sendCode('login')">
                  {{ countdown > 0 ? `${countdown}s 后重试` : '发送验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="注册" name="register">
        <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="80px">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="registerForm.code" placeholder="请输入验证码">
              <template #append>
                <el-button @click="sendCode('register')">
                  {{ countdown > 0 ? `${countdown}s 后重试` : '发送验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleRegister">注册</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.auth-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>

<!-- <el-form-item label="密码">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
            />
          </el-form-item> -->